package com.miracle.moa.oauth.config;

import com.miracle.moa.manager.entity.Role;
import com.miracle.moa.manager.feign.UserFeign;
import com.miracle.moa.oauth.entity.UserJwt;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 自定义授权认证类
 * @author : miracle
 * @version : 1.0.0
 * @date : 2021/3/22 21:53
 */
@Service
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 取出身份，如果身份为空说明没有认证
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
        if (authentication == null) {
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
            if (clientDetails != null) {
                //秘钥
                String clientSecret = clientDetails.getClientSecret();
                //数据库查找方式
                return new User(username, clientSecret, AuthorityUtils.commaSeparatedStringToAuthorityList(""));
            }
        }

        if (StringUtils.isEmpty(username)) {
            return null;
        }

        //根据用户名查询用户信息
        //创建User对象
        com.miracle.moa.manager.entity.User userInfo = userFeign.findUserAndRole(username);
        List<Role> roles = userInfo.getRoles();
        // role codes
        List<String> roleCodes = Optional.ofNullable(roles).orElse(new ArrayList<>()).stream().map(Role::getRoleCode).collect(Collectors.toList());
        return new UserJwt(username, userInfo.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.join(roleCodes, ",")));
    }
}
